package com.xzakota.minesweeper.widget.image;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * 圆角图像
 *
 * @author Xzakota
 */
public class RoundImage extends JPanel {
    private BufferedImage avatarImage;
    private int cornerRadius = 20;

    public RoundImage() {
        this((BufferedImage) null, 50, 50);
    }

    public RoundImage(URL avatarUrl, int width, int height) throws IOException {
        this(ImageIO.read(avatarUrl), width, height);
    }

    public RoundImage(BufferedImage avatarImage, int width, int height) {
        super(new BorderLayout(10, 10));

        this.avatarImage = avatarImage;
        setOpaque(false);
        setPreferredSize(new Dimension(width, height));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();
        int width = getWidth();
        int height = getHeight();
        Shape roundedRectangle = new RoundRectangle2D.Float(0, 0, width, height, cornerRadius, cornerRadius);
        g2d.setClip(roundedRectangle);
        g2d.drawImage(avatarImage, 0, 0, width, height, null);
        g2d.dispose();
    }

    public BufferedImage getAvatarImage() {
        return avatarImage;
    }

    public void setAvatarImage(BufferedImage avatarImage) {
        this.avatarImage = avatarImage;
        repaint();
    }

    public void setAvatarImage(URL avatarUrl) throws IOException {
        this.avatarImage = ImageIO.read(avatarUrl);
        repaint();
    }

    public int getCornerRadius() {
        return cornerRadius;
    }

    public void setCornerRadius(int cornerRadius) {
        this.cornerRadius = cornerRadius;
        repaint();
    }
}
